package com.qingzhou.schedule.interceptor;

import com.qingzhou.common.core.enums.DictEnum;
import com.qingzhou.schedule.domain.SysJobLog;
import com.qingzhou.schedule.service.ISysJobLogService;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.cloud.CloudJobHandler;
import org.noear.solon.cloud.CloudJobInterceptor;
import org.noear.solon.cloud.model.Job;

/**
 * 定时任务拦截器
 * @author xm
 */
@Component
public class GlobalJobInterceptor implements CloudJobInterceptor {

    @Inject
    ISysJobLogService sysJobLogService;

    @Override
    public void doIntercept(Job job, CloudJobHandler jobHandler) throws Throwable {
        handleIntercept(job, jobHandler);
    }

    /**
     * 定时任务调度记录
     * @param job
     * @param jobHandler
     * @throws Throwable
     */
    private void handleIntercept(Job job, CloudJobHandler jobHandler) throws Throwable {
        long start = System.currentTimeMillis();
        SysJobLog sysJobLog = new SysJobLog();
        sysJobLog.setJobName(job.getName());
//        sysJobLog.setJobSimpleName();
//        sysJobLog.setJobGroup();
        sysJobLog.setCronExpression(job.getCron7x());
        sysJobLog.setStatus(DictEnum.COMMON_SUCCESS_FAIL.SUCCESS.getValue());
//        sysJobLog.setJobMessage();
        try {
            jobHandler.handle(job.getContext());
        } catch (Throwable e) {
            sysJobLog.setStatus(DictEnum.COMMON_SUCCESS_FAIL.FAIL.getValue());
            sysJobLog.setExceptionInfo(e.getMessage());
            throw e;
        } finally {
            long times = System.currentTimeMillis() - start;
            sysJobLog.setCostTime(times);
            sysJobLogService.save(sysJobLog);
        }
    }

}
